<?php
/**
 * @author by bilee.
 * 时间: 17/2/10 上午8:59
 */
namespace Api\Controller;

use Common\Controller\HomebaseController;

class PortalController extends  HomebaseController{


    protected $order;
    function _initialize()
    {
        parent::_initialize();
        $this->order = D("Common/Order");
    }
    /**
     * @api {get} makeOrder/token/:token/uid/:uid/real_amount/：real_amount/order_amount/：order_amount/pay_method/：pay_method/order_number/:order_number/order_type/:order_type/city_id/:city_id/user_id/:user_id/ 发起订单接口
     * @apiName 发起订单接口
     * @apiGroup pt
     *
     * @apiParam {Int} uid 用户唯一ID.
     * @apiParam {String} token 用户token,每次登录都会更改.
     * @apiParam {String} order_type 订单类型.1取送订单，2，代买订单，3，代排队订单
     * @apiParam {String} city_id 城市id（1）先默认为1.
     * @apiParam {String} res_type 物品类型. 美食|生鲜|鲜花    |排队类型
     * @apiParam {String} reci_mobile 收件人电话.
     * @apiParam {String} voucher_no 商户订单id
     * @apiParam {String} reci_address 收件人地址.
     * @apiParam {String} reci_latit 收件人位置纬度 | 排队位置维度.
     * @apiParam {String} reci_longit 收件人位置经度 | 排队位置经度.
     * @apiParam {String} send_mobile 发件人电话.
     * @apiParam {int} order_amount 订单金额
     * @apiParam {int} real_amount 实付金额
     * @apiParam {int} pay_method 1.支付宝 2.微信 3.钱包
     * @apiParam {String} send_address 发件人地址.
     * @apiParam {String} send_latit 发件人位置纬度 | 排队下单人位置维度.
     * @apiParam {String} send_longit 发件人位置经度 | 排队下单人位置经度.
     * @apiParam {String} is_reservation 是否预约单.
     * @apiParam {String} reservation_time 预约时间.
     * @apiParam {String} remark_voice 补充说明语音地址.
     * @apiParam {String} remark 补充说明.
     * @apiParam {int} conveyance_id 运输工具ID.
     * @apiParam {String} up_server 升级服务.
     * @apiParam {decimal} fee 小费.
     * @apiParam {decimal} company_id 跑客团队ID.get
     *
     * //代买订单增加的参数
     * @apiParam {int} is_have_price [帮我买]是否知道价格0默认值 1 知道价格 2不知道价格.
     * @apiParam {decimal} goods_amount 帮我买商品金额:商品金额为0时，表示用户不知道价格。如果不为0，支付时需要计算该金额
     *
     * //排队订单增加的参数
     * @apiParam {String} replace_mobile 代他人排队电话.
     * @apiParam {String} queue_address 排队地点.
     * @apiParam {datetime} queue_time 排队时间.
     * @apiParam {String} hour_long 排队时长.
     * @apiParam {String} delayed 延长时长.
     **/

    function makeOrder()
    {
        verificationPcToken();
        $_GET['user_id'] = I('uid');
        $_GET['res_type'] = trim(I('res_type'));
        $order_amounts = 0.00;
        $order_amount_cal = 0.00;
        $nightAdd = 0.00;
        $addPrice = 0.00;
        $send_latit = I('send_latit');
        $send_longit = I('send_longit');
        $reci_latit = I('reci_latit');
        $reci_longit = I('reci_longit');
//        dump(I('order_type'));
        if (I('order_type') == 3) {
            if (!I('queue_time'))
                $_GET['queue_time'] = date('Y-m-d H:i:s', time());

          //  dump(I('hour_long'));
           // dump(I('order_time'));
            $order_amounts = get_line_up_money(I('uid'), I('city_id'), I('hour_long')*60, I('order_time'));
         //   dump($order_amounts);
//           die;
            $startMoney = $order_amounts['startMoney'];//起步价
            $money = $order_amounts['money'];//排队费
            $nightAdd = $order_amounts['nightAdd'];//夜间加价
            $addPrice = $order_amounts['addPrice'];//临时加价
            $coupon_value = $order_amounts['coupon_value'];//抵扣券的金额或折扣券的优惠金额【总之，是优惠金额】
//            dump("初始起步价：".$startMoney);
//            dump("排队费：".$money);

            //============选择团队：默认不加费用，大河+1元，直属+2元 start===============
            $totalPrice = $startMoney + $money;
//            dump( '起步价+排队费：');
//            dump($totalPrice);

            if (I('company_id') == 3) {
                $order_amount_cal = $totalPrice + 2;//直属团队
            } elseif (I('company_id') == 2) {
                $order_amount_cal = $totalPrice + 1;//大河团队
            } elseif (I('company_id') == 5) {
                $order_amount_cal = $totalPrice - 7;//校园团队
            } else
                $order_amount_cal = $totalPrice;
//            dump( '排队适配团队后的金额：');
//            dump($order_amount_cal);

            //============选择团队：默认全部不加费用，大河+1元，直属+2元 end===============
        } else {
            if (2 == I('order_type')) {
                $send_latit = I('reci_latit');
                $send_longit = I('reci_longit');
                $reci_latit = I('send_latit');
                $reci_longit = I('send_longit');
            }
            $order_amounts = get_order_money($send_latit, $send_longit, $reci_latit, $reci_longit, I('city_id'));//计算跑腿费=距离跑腿费+夜间加价+临时加价-优惠券
//            dump('获取跑腿费对象');
//            dump($order_amounts);
            $totalkilometre = $order_amounts['totalkilometre'];//订单的总公里数
            $totalPrice = $order_amounts['totalPrice'];//里程费+夜间加价+临时加价
            $coupon_value = $order_amounts['coupon_value'];//抵扣券的金额或折扣券的优惠金额【总之，是优惠金额】
            $startMoney = $order_amounts['startmoney'];//起步价
            $money = $order_amounts['money'];//排队费
            $nightAdd = $order_amounts['nightAdd'];//夜间加价
            $addPrice = $order_amounts['addPrice'];//临时加价

//            dump("初始起步价：".$startMoney);
//            dump("里程费：".$money);
            $total_amount = $startMoney + $money;
//            dump( '起步价+里程费：');
//            dump($total_amount);

            //=============车型：1电动车，2三轮车，3面包车 start===========

            if (I('conveyance_id') == 2)
                $order_amount_cal = $total_amount * 1.5;//三轮车跑腿费
            elseif (I('conveyance_id') == 3)
                $order_amount_cal = $total_amount * 2.5;//面包车跑腿费
            else
                $order_amount_cal = $total_amount;

//            dump( '适配车型后的金额：');
//            dump($order_amount_cal);

            //=============车型：1电动车，2三轮车，3面包车 end===============

            //============选择团队：默认不加费用，大河+1元，直属+2元 start===============
            if (I('company_id') == 2)
                $order_amount_cal = $order_amount_cal + 1;//大河团队
            elseif (I('company_id') == 3)
                $order_amount_cal = $order_amount_cal + 2;//直属团队
            elseif (I('company_id') == 5) {
                if ($totalkilometre < 2.5) {
                    $order_amount_cal = $order_amount_cal - 3;
                } else {
                    $order_amount_cal = $order_amount_cal - 7;//校园团队
                }
                //$order_amount_cal = $order_amount_cal - 7 ;//校园团队
            }
//            dump( '适配团队后的金额：');
//            dump($order_amount_cal);
            //============选择团队：默认全部不加费用，大河+1元，直属+2元 end===============
        }
//        dump('金额：'.$order_amount_cal);
//        dump('临时：'.$addPrice);
//        dump('夜间：'.$nightAdd);
//        dump('优惠金额：'.$coupon_value);

        $order_amount_cal = $order_amount_cal + $nightAdd + $addPrice - $coupon_value;
//        dump('金额+临时+夜间—优惠券后的金额：'.$order_amount_cal);
        if ($order_amount_cal <= 0)
            $order_amount_cal = 0;
//        dump('正值不变，负值归零：'.$order_amount_cal);

        $up_server = trim(I('up_server'));//1|2|3|4|5  服务升级： 加急|保险|是否保温配送|是否易碎|是否贵重
//        dump('服务升级：'.$up_server);
        if ($up_server) {
            $up_server_arr = explode("|", $up_server);
            foreach ($up_server_arr as $value) {
                if ($value == 1) {
                    $_GET['is_insured'] = 1;
                    $_GET['insured_amount'] = 5;//加急费用
                    $order_amount_cal += 5;//计算跑腿费　＋=　加急费用
                }
                if ($value == 2) {
                    $_GET['is_insurance'] = 1;
                    $_GET['insurance_amount'] = 5;//保险费用
                    $order_amount_cal += 5;//计算跑腿费 +=　保险费用
                }

                if ($value == 3)
                    $_GET['is_incubator'] = 1;
                if ($value == 4)
                    $_GET['is_fragile'] = 1;
                if ($value == 5)
                    $_GET['is_valuables'] = 1;
                if ($value == 6) {
                    $_GET['is_sms'] = 1;
                    $_GET['is_sms_amount'] = 1;
//                    dump('888888888888888888====='.$order_amount_cal);
                    $order_amount_cal = $order_amount_cal + 1;
//                    dump('==========================='.$order_amount_cal);
                }

            }
        }

        if (!I('is_reservation'))
            unset($_GET['reservation_time']);

        if (!I('coupon_id'))
            unset($_GET['coupon_id']);

        //验证 前台计算的订单金额 与 后台计算的金额 是否相等
        $fee = I('fee');
        if (isset($fee))
            $order_amount_cal += $fee;//计算跑腿费 += 小费
//        dump('加小费后：'.$order_amount_cal);
        $is_have_price = I('is_have_price');
        //dump($is_have_price);
        $order_type = I('order_type');

        if ($order_type == 2 && $is_have_price == 1)
            $order_amount_cal += I('goods_amount');//计算跑腿费 += 代买商品金额
//        dump('加商品费：'.$order_amount_cal);
        $order_amount = floatval(I('real_amount'));//18.5


//        dump('前台real_amount:');
//        dump($order_amount);
//        dump('后台amount:');

        $order_amount_cal = floatval($order_amount_cal); //18
       // dump($order_amount_cal);
      // dump($order_amount);

        if ( round($order_amount_cal,2) != round($order_amount,2)){//float类型比较函数，出现float(12.4) ！= float(12.4)的情况，这个函数避免 了这种情况
            return RET_NO_V(0, '订单金额计算有误，请重新下单');
        }//验证 ：前台计算的订单金额 ！= 后台计算的金额

        //订单支付记录
        if (3 == I('pay_method')) {
            $app_users = M('app_users')->where(array('user_id' => I('uid')))->field('purse_balance')->find();
            if ($app_users['purse_balance'] < $order_amount) {
                return RET_NO_V(0, "余额不足，请选择其它支付方式！");
            }
        }
        $this->order->startTrans();
        $order = $this->order->create(I('get.'));
        if ($order) {
            $ret = $this->order->add();
            if ($ret) {
                //优惠券ID
                $coupon_id = I('coupon_id');
                $user_coupon = M('user_coupon');
                //更改优惠券状态
                if (!empty($coupon_id)) {
                    if(!isvalid_used_coupon($coupon_id,I('uid')))
                        return RET_NO_V(0, "优惠券失效，请重新下单！");
//                    $user_coupon->startTrans();
                    $ret_user_coupon = $user_coupon->where(array('user_coupon_id' => $coupon_id, 'user_id' => I('uid')))->save(array('is_used' => 2,'used_orderid'=>$ret));
                    if (!$ret_user_coupon) {
                        //提交事务
//                        $user_coupon->commit();
//                    }else{
                        //事务回滚
//                        $user_coupon->rollback();
                        $this->order->rollback();
                        return RET_NO_V(0, "优惠券使用失败，请重试！");
                    }
                }

                $order_pay = M('order_pay');
                $datas = array(
                    'order_id' => $ret,
                    'pay_amount' => I('real_amount'),
                    'status' => 0,
                    'voucher_no' => I('voucher_no'),       //==商户唯一订单号
                    'pay_method' => I('pay_method')        //支付方式
                );
                $rets = $order_pay->add($datas);
                if ($rets) {
                    $otype = 0;
                    if (I('is_reservation') == 1)
                        $otype = 1;
                    $_GET['order_id'] = $ret;
                    $order_resmsm_db = M('order_resmsm');
                    $lat = "";
                    $lng = "";
                    switch (I('order_type')) {
                        //取送
                        case 1:
                            $lat = $send_latit;
                            $lng = $send_longit;
                            break;
                        //代买
                        case 2:
                            $lat = $reci_latit;
                            $lng = $reci_longit;
                            break;
                        //排队
                        case 3:
                            $lat = I('reci_latit');
                            $lng = I('reci_longit');
                            break;
                    }
                    $res_data = array('order_id' => $ret,
                        'company_id' => $order['company_id'],
                        'order_number' => $order['order_number'],
                        'order_type' => I('order_type'),
                        'app_user_id' => I('uid'),
                        'order_lat' => $lat,  //订单的纬度
                        'order_lng' => $lng,  //订单的经度
                        'order_time' => $order['order_time'],
                        'reservation_time' => I('reservation_time'),
                        'otype' => $otype,
                        'order_data' => json_encode(I('get.')));
                    if (!I('reservation_time'))
                        unset($res_data['reservation_time']);

                    $ret_res = $order_resmsm_db->add($res_data);
                    if ($ret_res) {
                        $this->order->commit();
                        return RET(1, "订单生成成功！", $datas);
                    } else {
                        $this->order->rollback();
                        return RET_NO_V(0, "订单临时表生成失败，请重试！");
                    }

                } else {
                    $this->order->rollback();
                    return RET_NO_V(0, "支付记录单生成失败，请重试！");
                }
            } else {
                $this->order->rollback();
                return RET_NO_V(0, "订单生成失败，请重试！");
            }
        } else {
            return RET_NO_V(0, $this->order->getError());
//            $this->error($this->order->getError());
        }

    }
    /**
     * @api {get} getOrderAmount/uid/:uid/token/:token/ 获取订单价格
     * @apiName 获取订单价格(起步价2公里（含2公里），每单8元；3公里12元；3-10公里之间每公里加1元；10-30公里以后，每公里加2元；超出30公里后每公里加3元)
     * @apiGroup pt
     *
     * @apiParam {Int} uid 用户唯一ID.
     * @apiParam {String} token 用户token,每次登录都会更改.
     * @apiParam {Int} cityId 城市ID.
     * @apiParam {String} appointmentTime 预约时间 选填.
     * @apiParam {String} startLat 开始的维度.
     * @apiParam {String} startLng 开始的经度.
     * @apiParam {String} endLat 结束的维度.
     * @apiParam {String} endLng 结束的经度.
     * @apiSuccessExample 成功返回:
     *     HTTP/1.1 200 OK
     *     {
     *"retCode": 0,
     *"retDesc": "计算成功！",
     *"retValue": {
     *"duration": 13,           //所需时间
     *"totalPrice": 20.4, //总价= 起步价 + 里程费 + 夜间加价 + 临时加价
     *"totalkilometre": 3, //总公里数
     *"startkilometres": 2, //起步公里
     *"startmoney": 8,      // 起步价
     *"kilometres": 1,      // 里程数
     *"money": 4,           // 里程费
     *"nightAdd": 5,         //夜间加价
     *"addPrice": 3.4        //临时加价
     * "userCouponId": 3.4        //使用优惠券id
     * "couponTitle": 3.4        //优惠券标题
     *" couponMoney" //优惠之后的金额
     *}
     *}
     **/
    function getOrderAmount()
    {
        //接口权限校验
        verificationPcToken();
        //组装经纬度
        $start = I('startLat') . "," . I('startLng');
        $end = I('endLat') . "," . I('endLng');

        $ret = line_uu($start, $end);

        //获取公里数取整
        $distance = $ret['message'];

        //获取公里数取整
        $kilometre = number_format($distance / 1000, 2);

        //$duration = $ret['result']['routes'][0]['duration'];

        //$duration = number_format($duration / 60, 2);
        //$data['duration'] = $duration;
        $cityId = (float)I('cityId');

        $twoStartKiloMoney = getTwoStartKiloMoney($cityId, $kilometre);
//        dump($twoStartKiloMoney);
        $totalPrice = $twoStartKiloMoney['totalPrice'];
        $data['totalPrice'] = format_money($totalPrice);

        $data['totalkilometre'] = $kilometre;

        $pricing_tactics = M('pricing_tactics');
        //夜间加价
        $nightAdd = 0;
        $ret = $pricing_tactics->where(array('city_id' => $cityId))->field('tactics_array')->find();
//    ["startkilometres"] => string(1) "3"
//    ["startmoney"] => string(1) "9"
//    ["totalPrice"] => float(14)
//    ["money"] => float(5)
//    ["kilometres"] => float(3)
        if ($ret['tactics_array']) {
            $tactics_array = json_decode($ret['tactics_array'], TRUE);
            $mileage = $tactics_array['mileage'];
            $night = $tactics_array['night'];
            $data['startkilometres'] = format_money($twoStartKiloMoney['startkilometres']);
            $data['startmoney'] = format_money($twoStartKiloMoney['startmoney']);

            $data['kilometres'] = 0.00;
            if ($kilometre - format_money($twoStartKiloMoney['startkilometres']) > 0.00)
                $data['kilometres'] = $kilometre - format_money($twoStartKiloMoney['startkilometres']);

            $data['money'] = format_money($twoStartKiloMoney['money']);
            $data['nightAdd'] = format_money($nightAdd);
            $date = null;

            /*$time = "2016-1-10 23:23";
            $date = substr($time,-5,5);
            dump($date);*/
            if (I('appointmentTime')) {
                $date = substr(I('appointmentTime'), -5, 5);
            } else {
                $date = date('H:i');
            }
            for ($i = 0; $i < count($night); $i++) {
                $startTime = $night[$i]['startTime'];
                $endTime = $night[$i]['endTime'];
                if ($startTime <= $date) {
                    if ($endTime > $date) {
                        $nightAdd += $night[$i]['addMoney'];
                        $data['nightAdd'] = format_money($nightAdd);
                        $totalPrice += $nightAdd;
                        break;
                    }
                }
            }
            $temporary = $tactics_array['temporary'];
//            dump($temporary);
            $addPrice = number_format($totalPrice * ($temporary["addtimes"] - 1), 2);
             if(I('goods_amount'))
             {
                 $goods_amount = I('goods_amount');
                 $totalPrice += $goods_amount; 
             }
            $data['addPrice'] = $addPrice;
            $totalPrice += $addPrice;
            $data['totalPrice'] = number_format($totalPrice, 2);
            $return = couponUse(I('uid'), $totalPrice);
            $data['userCouponId'] = $return['userCouponId'];
            $data['couponTitle'] = $return['couponTitle'];
            $data['couponMoney'] = $return['couponMoney'];
            $data['coupon_value'] = $return['coupon_value'];
//            dump('data:');
//            dump($data);
//            dump($data['coupon_value']);
            return RET(1, "计算成功！", $data);
        } else {
            return RET_NO_V(0, "计算失败！");
        }
    }
    /**
     * @api {get} getLineUpAmount/uid/:uid/token/:token/ 获取排队订单价格
     * @apiName 获取订单价格(起步价10元（含30分钟），每30分钟加10元)
     * @apiGroup pt
     *
     * @apiParam {Int} uid 用户唯一ID.
     * @apiParam {String} token 用户token,每次登录都会更改.
     * @apiParam {Int} cityId 城市ID.
     * @apiParam {String} timeslong 排队时长.
     * @apiParam {String} appointmentTime 预约时间 选填.
     * @apiSuccessExample 成功返回:
     *     HTTP/1.1 200 OK
     *     {
     *"retCode": 0,
     *"retDesc": "计算成功！",
     *"retValue": {
     *"lineUpMoney": 20.4, //总价
     *"startlineTime": 30, //起步分钟
     *"startMoney": 10,      // 起步价
     *"money": 4,           // 费用
     *"nightAdd": 5,         //夜间加价
     *"addPrice": 3.4        //临时加价
     * "couponMoney": 3.4        //优惠之后价格
     * "couponTitle": 3.4        //优惠标题
     * "CouponId": 3.4        //优惠券id
     *}
     *}
     **/

    function getLineUpAmount()
    {
        verificationPcToken();
        $pricing_tactics = M('pricing_tactics');
        $ret = $pricing_tactics->where(array('city_id' => I('cityId')))->field('tactics_array')->find();
        //dump($ret);
        if ($ret['tactics_array']) {
            $tactics_array = json_decode($ret['tactics_array'], TRUE);
           // dump($tactics_array);
            $is_starting_price = $tactics_array['is_starting_price'];
            $data['startMoney'] = format_money($is_starting_price[0]['lineKoney']);
            $data['startlineTime'] = $is_starting_price[0]['lineTime'];
            $line_up = $tactics_array['line_up'];
            //dump($line_up);
            $night = $tactics_array['night'];
            $pricePer = $line_up[0]['pricePer'];
//            dump($pricePer);
//            dump(I('timeslong')*60/30);
            $lineUpMoney = ceil(I('timeslong')*60 / 30) * $pricePer;
          // dump($lineUpMoney);
            $data['money'] = format_money($lineUpMoney - $data['startMoney']);
            $data['lineUpMoney'] = format_money($lineUpMoney);
            //dump($data['lineUpMoney']);
            $nightAdd = 0;
            $data['nightAdd'] = format_money($nightAdd);
            $date = null;
            /*$time = "2016-1-10 23:23";
            $date = substr($time,-5,5);
            dump($date);*/
            if (I('appointmentTime')) {
                $date = substr(I('appointmentTime'), -5, 5);
            } else {
                $date = date('H:i');
            }
            for ($i = 0; $i < count($night); $i++) {
                $startTime = $night[$i]['startTime'];
                $endTime = $night[$i]['endTime'];
                if ($startTime <= $date) {
                    if ($endTime > $date) {
                        $nightAdd += $night[$i]['addMoney'];
                        $data['nightAdd'] = format_money($nightAdd);
                        $lineUpMoney += $nightAdd;
                        break;
                    }
                }
            }
            $temporary = $tactics_array['temporary'];
            $addPrice = format_money($lineUpMoney * ($temporary["addtimes"] - 1));

            $data['addPriceDesc'] = $temporary['addtimes_reson'];
            $data['addPrice'] = $addPrice;
            $lineUpMoney += $addPrice;
            $return = couponUse(I('uid'), $lineUpMoney);
            $data['lineUpMoney'] = format_money($lineUpMoney);
            //dump($data['lineUpMoney']);
            $data['couponMoney'] = number_format($return['couponMoney'], 2);
            $data['couponTitle'] = $return['couponTitle'];
            $data['CouponId'] = $return['userCouponId'];
            $data['coupon_value'] = $return['coupon_value'];
            //dump($data);
            return RET(1, "返回成功", $data);
        } else {
            return RET_NO_V(0, "计算失败！");
        }
    }

    /**
     * @api {get} alipayPayConfirm/uid/:uid/token/:token/tradeNO/:tradeNO 支付确认接口
     * @apiName 支付确认接口
     * @apiGroup pt
     *
     * @apiParam {Int} uid 用户唯一ID.
     * @apiParam {String} token 用户token,每次登录都会更改.
     * @apiParam {String} tradeNO 客户端生成的商户订单号
     *
     * @apiSuccessExample 成功返回: 状态:0未支付，1成功，2失败
     *     HTTP/1.1 200 OK
     *     {
     *       "retCode": 0,
     *       "retDesc": "获取数据成功！"，
     *       "retValue":"0"
     *     }
     *
     * @apiError retCode=1为返回数据错误.
     *
     */
    public function alipayPayConfirm()
    {
        verificationPcToken();
        $order_pay = M('order_pay');
        $ret = $order_pay->where(array('voucher_no' => I('tradeNO'), 'status' => 1))->find();
        if ($ret) {
            return RET(0, "获取状态成功!");
        } else {
            return RET_NO_V(1, "获取状态失败,请重试");
        }
    }

    /**
     * @api {get} weixinNotify 微信异步回调接口
     * @apiName 获取用户余额
     * @apiGroup pt
     *
     */
    public function weixinNotify()
    {
        vendor("wxpay.WxPay");
        $xml = $GLOBALS['HTTP_RAW_POST_DATA'];
        \Think\Log::record('xml：'.$xml);
		//\Think\Log::record('xml：'.$_POST);
        $ret = xmlToArray($xml);

        $out_trade_no = $ret['out_trade_no'];

        //用户标识
        $openid = $ret['openid'];
        //微信订单号
        $transaction_id = $ret['transaction_id'];
        //交易结果
        $result_code = $ret['result_code'];//交易结果
        //total_fee
        $total_fee = $ret['total_fee'] / 100;//订单总金额，单位为分,除以100，单位换算为元
        $notify = new \WxPay();
        $data = array('transaction_id' => $transaction_id);//$ret['transaction_id']);//微信支付订单号
        $msg = "";
        $notify_ret = $notify->NotifyProcess($data, $msg);
        $user_recharge = M('user_recharge');
        $order_pay = M('order_pay');
        if ($notify_ret) {
            $result = $notify->Handle($result_code);
            if ($result_code == 'FAIL') {

            } else if ($result_code == 'SUCCESS') {
                $order_pay->startTrans();
                $pay_obj = $order_pay->where(array('voucher_no' => $out_trade_no))->find();
//                \Think\Log::record('status：'.$pay_obj['status']);
                if ($pay_obj['status'] == 0) {
                    $ret = $order_pay->where(array('voucher_no' => $out_trade_no))->save(array('pay_time' => date('Y-m-d H-i-s', time()), 'pay_account' => $openid, 'pay_number' => $transaction_id, 'status' => 1));
                    $order_id = $order_pay->where(array('voucher_no' => $out_trade_no))->field('order_id')->find();
                    $order = M('order');
                    $retss = $order->where(array('order_id' => $order_id['order_id']))->save(array('pay_status' => 1, 'status' => 1));
                    $resmsm_ret = M('order_resmsm')->where(array('order_id' => $order_id['order_id']))->save(array('status' => 1, 'pay_status' => 1));//订单中间表状态修改

                    if ($retss && $ret && $resmsm_ret) {
                        $order_pay->commit();
                        echo "SUCCESS";
                    } else {
                        $order_pay->rollback();
                        echo "FAIL";
                    }
                } else
                    echo "SUCCESS";

            }
            echo "SUCCESS";
        } else {
            $order_pay->where(array('voucher_no' => $out_trade_no))->save(array('pay_time' => date('Y-m-d H-i-s', time()), 'pay_number' => $transaction_id, 'status' => 2));
            echo "FAIL";
        }
    }


    /**
     * @api {get} userBalancePay/token/:token/uid/:uid/order_id/:order_id/out_trade_no/:out_trade_no 用户余额支付
     * @apiGroup pt
     * @apiParam {Int} uid 用户唯一ID. 必填
     * @apiParam {String} topnRobOrderken 跑腿token,每次登录都会更改. 必填
     * @apiParam {Int} order_id 订单id .必填
     * @apiParam {String}out_trade_no  商户唯一订单号 选填
     *
     * @apiSuccessExample Success-Response:
     *     HTTP/1.1 200 OK
     *
     * {
     * "retCode": 200,
     * "retDesc": "订单余额支付成功",
     * "retValue": ""
     * }
     **/
    function userBalancePay()
    {
        verificationPcToken();
        $order_id = I('order_id');
        $uid = I('uid');
        $out_trade_no = I('out_trade_no');

        if (!$uid || !$order_id)
            return RET_NO_V(400, '参数为空');

        $order_db = M('order');
        $order_pay = M('order_pay');
        $order_obj = $order_db->field('real_amount,order_number,order_amount,coupon_id')
            ->where(" order_id = '" . $order_id . "' and user_id = " . $uid . ' and pay_status=0 and pay_method=3')
            ->find();

        if (!$order_obj)
            return RET_NO_V(400, "订单号有误");
        $order_db->startTrans();
        $real_amount = $order_obj['real_amount'];
        $change_remark = '订单 ' . $order_obj['order_number'] . ' 用户余额支付 ' . $real_amount . '元';
        if ($real_amount == "0.00" && $order_obj['coupon_id']) {
            //反查优惠信息表
            $coupon_info = M("user_coupon");
            $cou_ret = $coupon_info->field('coupon_value,coupon_type')->where("user_coupon_id=" . $order_obj['coupon_id'] . " and valid_end_time >= sysdate()")->find();

            if ($cou_ret) {
                $cou_amount = $cou_ret['coupon_value'];//抵扣的钱数
                if ((float)$cou_amount >= (float)$order_obj['order_amount']) {
                    $change_remark = '订单(' . $order_obj['order_number'] . ')使用优惠券抵扣，此单免单';
                } else {
                    return RET_NO_V(400, "优惠金额有误");
                }
            } else {
                return RET_NO_V(400, "优惠金额有误");
            }
        } else {

            //没用优惠券扣余额
            $user_db = M('app_users');
            $user_balance = $user_db->where('user_id=' . $uid)->field('purse_balance')->find();
            //抱歉余额不足
            if (!$real_amount || !$user_balance['purse_balance'] || $real_amount > $user_balance['purse_balance'])
                return RET_NO_V(400, '抱歉余额不足');

            //用户钱包处理 db_user_purse
            $user_purse_db = M('user_purse');
            $purse_data = array(
                'user_id' => $uid,
                'purse_amount' => $real_amount,
                'purse_type' => 2,//订单消费
                'change_time' => date('Y-m-d H-i-s', time()),
                'change_remark' => $change_remark,
                'order_id' => $order_id,
                'sum_amount'=>get_user_balance($uid) - $real_amount
            );
            //新增用户钱包明细
            $purse_adret = $user_purse_db->add($purse_data);

            //计算用户最终剩余多少余额
            $balance = $user_balance['purse_balance'] - $real_amount;
            //更新用户余额
            $user_upret = $user_db->where('user_id=' . $uid)->setField('purse_balance', $balance);
            if (!$user_upret||!$purse_adret){
                $order_db->rollback();
                $order_pay->where(array('order_id' => $order_id))->save(array('pay_time' => date('Y-m-d H-i-s', time()), 'status' => 2));
                return RET_NO_V(400, '抱歉，用户钱包支付失败！');
            }
        }

        $data = array('pay_time' => date('Y-m-d H-i-s', time())
        , 'voucher_no' => $out_trade_no
        , 'pay_account' => getUserMobileForType($uid, 1)//支付的是手机号
        , 'status' => 1);
        //更改订单支付状态
        $ret = $order_pay->where(array('order_id' => $order_id))->save($data);

        $resmsm_ret = M('order_resmsm')->where(array('order_id' => $order_id))->save(array('status' => 1, 'pay_status' => 1));//订单中间表状态修改

        if (!$ret || !$resmsm_ret) {
            $order_db->rollback();
            return RET_NO_V(400, '订单支付信息有误');
        }

        //更改订单表支付状态
        $retss = $order_db->where(array('order_id' => $order_id))->save(array('pay_status' => 1, 'status' => 1));

        if (!$retss) {
            $order_db->rollback();
            return RET_NO_V(400, '订单支付信息有误');
        } else {
            $order_db->commit();
            return RET_NO_V(200, '订单余额支付成功');
        }

    }

}